<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="试卷名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入试卷名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试卷总分" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入试卷总分"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考试时长(分钟)" prop="duration">
        <el-input
          v-model="queryParams.duration"
          placeholder="请输入考试时长(分钟)"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试卷平均难度" prop="difficulty">
        <el-input
          v-model="queryParams.difficulty"
          placeholder="请输入试卷平均难度"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          v-hasPermi="['paper:paper:add']"
          >批量导入</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['paper:paper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['paper:paper:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['paper:paper:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="paperList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="试卷id" align="center" prop="id" />
      <el-table-column
        label="试卷名称"
        :show-overflow-tooltip="true"
        align="center"
        prop="name"
      />
      <el-table-column label="试卷总分" align="center" prop="score" />
      <el-table-column label="考试时长(分钟)" align="center" prop="duration" />
      <el-table-column label="试卷平均难度" align="center" prop="difficulty" />
      <!-- <el-table-column label="试卷状态" align="center" prop="id" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleCheck(scope.row)"
            >预览</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSelect(scope.row)"
            >选择</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['paper:paper:edit']"
          >修改</el-button> -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['paper:paper:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览整张试卷 -->

    <el-dialog
      width="80%"
      title
      :visible.sync="paper"
      v-if="paper"
      append-to-body
    >
      <showpaper :row="paperdata"></showpaper>
    </el-dialog>
    <!-- 添加或修改试卷对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="100%"
      v-loading="loading"
    >
      <el-row :gutter="15">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="medium"
          label-width="120px"
        >
          <el-col :span="6">
            <el-form-item label="试卷模板" prop="paperTemplateId">
              <el-select
                v-model="form.paperTemplateId"
                placeholder="请选择试卷模板"
                @change="handleexammodel()"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in field105Options"
                  :key="index"
                  :label="item.name"
                  :value="item.paperTemplateId"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试卷名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入试卷名称"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="试卷总分" prop="score">
              <el-input
                v-model="form.score"
                placeholder="请选择试卷模板"
                :disabled="true"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="考试时长(分钟)" prop="duration">
              <el-input
                v-model="form.duration"
                placeholder="请选择试卷模板"
                :disabled="true"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="试卷平均难度" prop="difficulty">
              <el-input
                v-model="form.difficulty"
                placeholder="请选择试卷模板"
                :disabled="true"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24"></el-col>
          <el-col :span="6">
            <el-form-item label="组卷方式" prop="field104">
              <el-select
                v-model="form.field104"
                placeholder="请选择组卷方式"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in field104Options"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-dialog
              title
              :visible.sync="outvisable"
              v-if="outvisable"
              width="60%"
              append-to-body
              center
            >
              <!-- <div v-if="judegtype">
                <search :row="{searchitem,exitem}" @componentdata="componentdata"></search>
              </div>
              <div v-if="!judegtype">
                <showitem :row="shwo"></showitem>
              </div> -->
            </el-dialog>
            <el-dialog
              width="50%"
              title="小题详情"
              :visible.sync="innerVisible"
              v-if="innerVisible"
              append-to-body
            >
              <showDetail :row="propdata"></showDetail>
            </el-dialog>

            <div v-for="(item, i) in form.structureList" :key="i">
              <div class="container">
                <span class="number"
                  >{{ item.name }} {{ item.score }}分 共{{ item.count }}题
                  已选{{ item.templatecount }}题 该大题平均难度{{
                    item.difficulty
                  }}</span
                >
                <el-button
                  type="success"
                  @click="checkcontianer(i)"
                  plain
                  round
                  :disabled="item.templatecount == 0"
                  >预览大题</el-button
                >
                <!-- <el-button type="success" @click="checkcontianer(i)" :disabled="!(form.structureList[i].bankList!=null&&form.structureList[i].count==form.structureList[i].bankList.length)" plain round>预览大题</el-button> -->
              </div>
              <!-- 这里是选择的地方 -->
              <!-- <el-dialog width="60%" title="小题合集" @close="item.outvisable=false" :visible.sync="item.outvisable" append-to-body> -->
              <el-collapse v-model="item.quesitem" style="margin-left: 100px">
                <el-collapse-item title="查看/隐藏小题">
                  <div>
                    <div class="questitem">
                      <div
                        class="questdetail"
                        v-for="item2 in item.count"
                        :key="item2"
                      >
                        <span
                          style="color: #e6a23c"
                          v-if="item.bankList[item2 - 1] == null"
                          >请选择小题</span
                        >
                        <!-- {{item.bankList[item2]}} -->
                        <span
                          style="margin-left: 10px"
                          v-if="item.bankList[item2 - 1] != null"
                          >第{{ item2 }}题</span
                        >
                        <el-button
                          type="primary"
                          style="margin-left: 10px"
                          @click="handdeeletip(i, item2 - 1, item)"
                          size="mini"
                          round
                        >
                          <i class="el-icon-edit"></i>
                        </el-button>
                        <el-button
                          type="success"
                          style="margin-right: 10px"
                          @click="handonecheck(i, item2 - 1, item)"
                          size="mini"
                          round
                        >
                          <i class="el-icon-view"></i>
                        </el-button>
                      </div>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item size="large" style="margin-top: 10px">
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button @click="dialogresetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </div>
</template>


<script>
import {
  listPaper,
  getPaper,
  delPaper,
  addPaper,
  updatePaper,
  exportPaper,
} from "@/api/paper/paper";
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
  exportTemplate,
} from "@/api/paper/template";
import showDetail from "@/components/showDetail";
// import search from "../paper/paper/search.vue";
// import showitem from "../paper/paper/showitem.vue";
import showpaper from "./showpaper.vue";
import { listTemplate as qlistTemplate } from "@/api/topic/template";
import { listQuestionbank } from "@/api/topic/questionbank";
import { selectExaminationPaper } from "@/api/exam/examinationPaper";
import { listExaminationPaper } from "@/api/exam/examinationPaper";

export default {
  name: "searchpaper",
  props: ["row"],
  // components: { showDetail: showDetail, search, showitem, showpaper },
  components: { showDetail: showDetail, showpaper },
  data() {
    return {
      //是否显示已选小题
      quesitem: false,
      //小题合集的dialog
      outvisable: false,
      //内部的dialog
      innerVisible: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷表格数据
      paperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示试卷预览
      paper: false,
      //试卷预览的数据
      paperdata: [],
      //传递到详情的数据
      propdata: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        score: null,
        duration: null,
        difficulty: null,
      },
      //判断是大题预览还是小题预览
      judegtype: "",
      // structureList
      structureListI: "",
      //中间变量
      templateindex: "",
      //搜索小题
      searchitem: "",
      //已存在的小题
      exitem: [],
      //预览题目
      shwo: "",
      //小题信息
      smollt: [],
      //试卷模板
      field103Options: [],
      //引用试卷列表
      list_ExaminationPaper: [],
      // 表单参数
      form: {
        name: undefined,
        duration: undefined,
        score: undefined,
        paperTemplateId: undefined,
        field107: undefined,
        difficulty: undefined,
      },
      // 表单校验
      rules: {
        field105: [
          {
            required: true,
            message: "请选择试卷模板",
            trigger: "change",
          },
        ],
        field104: [
          {
            required: true,
            message: "请选择组卷方式",
            trigger: "change",
          },
        ],
        field106: [
          {
            required: true,
            message: "请输入试卷名称",
            trigger: "blur",
          },
        ],
        field108: [
          {
            required: true,
            message: "请输入试卷总分",
            trigger: "blur",
          },
        ],
        field107: [
          {
            required: true,
            message: "请输入考试时长(分钟)",
            trigger: "blur",
          },
        ],
        paperTemplateId: [
          {
            required: true,
            message: "请选择试卷模板",
            trigger: "blur",
          },
        ],
        difficulty: [
          {
            required: true,
            message: "请输入试卷平均难度",
            trigger: "blur",
          },
        ],
      },
      field105Options: [
        {
          label: "选项一",
          value: 1,
        },
        {
          label: "选项二",
          value: 2,
        },
      ],
      field104Options: [
        {
          label: "手动组卷",
          value: 1,
        },
        {
          label: "自动组卷",
          value: 2,
        },
      ],
    };
  },
  created() {
    this.getList();
    this.c();
  },
  methods: {
    //获取已引入的试卷列表
    getListExaminationPaper() {
      listExaminationPaper(this.row).then((response) => {
        //console.log(2222, response);
        this.list_ExaminationPaper = response.rows;
      });
    },

    //表单重置
    dialogresetForm() {
      this.form = {
        name: undefined,
        duration: undefined,
        score: undefined,
        paperTemplateId: undefined,
        field107: undefined,
        difficulty: undefined,
      };
    },
    ////点击小题后添加,接受子组件传值
    componentdata(componentdata) {
      this.form.structureList[this.structureListI].bankList[
        this.templateindex
      ] = componentdata;
      this.form.structureList[this.structureListI].bankList[
        this.templateindex
      ].paperOrdered = this.templateindex;
      //计算难度
      let sum = 0;
      for (
        let i = 0;
        i < this.form.structureList[this.structureListI].bankList.length;
        i++
      ) {
        if (
          this.form.structureList[this.structureListI].bankList[i] != undefined
        ) {
          sum +=
            this.form.structureList[this.structureListI].bankList[i].difficulty;
        }
      }
      this.form.structureList[this.structureListI].difficulty = parseFloat(
        sum / this.form.structureList[this.structureListI].bankList.length
      ).toFixed(1);
      var sumtotal = parseFloat(0);
      for (let j = 0; j < this.form.structureList.length; j++) {
        sumtotal += parseFloat(this.form.structureList[j].difficulty);
      }

      this.form.difficulty = parseFloat(
        parseFloat(sumtotal).toFixed(1) / this.form.structureList.length
      ).toFixed(1);

      this.form.structureList[this.structureListI].templatecount =
        this.form.structureList[this.structureListI].bankList.length;
      this.$message({
        message: "添加成功",
        type: "success",
      });
      this.outvisable = false;
    },
    /** 查询试卷列表 */
    getList() {
      this.loading = true;
      listPaper(this.queryParams).then((response) => {
        this.paperList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listTemplate().then((response) => {
        this.field105Options = response.rows;
        for (let i = 0; i < this.field105Options.length; i++) {
          this.field105Options[i].paperTemplateId = this.field105Options[i].id;
          this.field105Options[i].id = null;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        classesId: null,
        createBy: null,
        createduration: null,
        updateBy: null,
        updateduration: null,
        name: null,
        score: null,
        duration: null,
        difficulty: null,
      };
      this.resetForm("form");
    },
    //选择了试卷模板
    handleexammodel() {
      getTemplate(this.form.paperTemplateId).then((response) => {
        this.form = response.data;
        this.form.duration = this.form.time;
        this.form.paperTemplateId = response.data.id;
        this.form.id = null;
        for (let i = 0; i < this.form.structureList.length; i++) {
          this.form.structureList[i].outvisable = false;
          this.form.structureList[i].quesitem = 1;
          this.form.structureList[i].difficulty = 0;
          this.form.structureList[i].score = parseFloat(
            this.form.structureList[i].score
          );
          this.form.structureList[i].templatecount = 0;
          this.form.structureList[i].bankList = [];
        }
      });
    },

    //预览小题详细
    handonecheck(findex, sindex, item) {
      if (this.form.structureList[findex].bankList[sindex] == null) {
        this.$confirm("请先选择小题", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.handdeeletip(findex, sindex, item);
          })
          .catch(() => {});
      } else {
        this.propdata = this.form.structureList[findex].bankList[sindex];
        this.innerVisible = true;
      }
    },
    //预览一道大题内部的所有小题
    checkcontianer(item) {
      if (this.form.structureList[item].bankList == null) {
        this.$message({
          message: "请先选择小题",
          type: "warning",
        });
      } else {
        this.outvisable = true;
        this.judegtype = false;
        this.shwo = this.form.structureList[item];
      }
    },
    //添加试卷时候点击修改小题后
    handdeeletip(index, temindex, templaitem) {
      this.judegtype = true;
      this.searchitem = templaitem;
      this.exitem = this.form.structureList[index].bankList;
      const data = {
        beanName: this.form.structureList[index].beanName,
        questionTemplateId: this.form.structureList[index].questionTemplateId,
      };
      this.structureListI = index;
      listQuestionbank(data).then((response) => {
        this.smollt = response.rows;
      });
      this.outvisable = true;
      this.templateindex = temindex;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试卷";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ids = row.id || this.ids;
      getPaper(ids).then((response) => {
        this.form = response.data;
        for (let i = 0; i < this.form.structureList.length; i++) {
          if (this.form.structureList[i].bankList == []) {
            this.form.structureList[i].templatecount = 0;
          } else {
            this.form.structureList[i].templatecount =
              this.form.structureList[i].bankList.length;
            let sum = 0;
            for (
              let j = 0;
              j < this.form.structureList[i].bankList.length;
              j++
            ) {
              sum += this.form.structureList[i].bankList[j].difficulty;
            }
            this.form.structureList[i].difficulty = parseFloat(
              sum / this.form.structureList[i].bankList.length
            ).toFixed(1);
          }
        }
        this.open = true;
        this.title = "修改试卷";
      });
    },
    //预览整张试卷
    handleCheck(row) {
      this.paper = true;
      const ids = row.id || this.ids;
      this.paperdata = {
        id: ids,
      };
    },
    //引入单张试卷
    handleSelect(DSX) {
      console.log(DSX);
      let exit = 0;
      this.getListExaminationPaper(); //每次循环之前更新已引用试卷列表
      setTimeout(() => {
        //设置时间延迟，防止因网络问题导致可以重复引入两条相同数据（*并发*）
        for (var i = 0; i < this.list_ExaminationPaper.length; i++) {
          // console.log(data.paperId, this.list_ExaminationPaper[i].id);
          if (data.paperId == this.list_ExaminationPaper[i].id) {
            exit = 1;
          }
        }
        if (exit == 1) {
          this.$message.error("该条数据已重复引用！");
        } else {
          selectExaminationPaper(data).then((response) => {
            this.$message({
              message: "添加成功",
              type: "success",
            });
          });
        }
      }, 1000);

      const data = {
        //考试表主键id
        examinationId: this.row.examinationId,
        //考试场次id
        sessionId: this.row.sessionId,
        //试卷表主键id
        paperId: DSX.id,
      };
      console.log(data);

      // selectExaminationPaper(data).then((response) => {
      //   this.$message({
      //     message: "添加成功",
      //     type: "success",
      //   });
      // });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.form.id != null) {
            updatePaper(this.form).then((response) => {
              this.msgSuccess("修改成功");
              // this.loading=false
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            addPaper(this.form).then((response) => {
              this.msgSuccess("新增成功");
              // this.loading=false
              this.open = false;
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除试卷编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delPaper(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有试卷数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportPaper(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
.questitem {
  display: flex;
  flex-flow: wrap;
  margin-bottom: 20px;
  margin-left: 10px;
  background-color: #ebeef5;
}
.questdetail {
  margin-top: 5px;
  margin-bottom: 5px;
  margin-left: 10px;
  height: 48px;
  padding-left: 5px;
  line-height: 48px;
  /* width: 12%; */
  border-radius: 30px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
}
.questdetail1 {
  margin-top: 5px;
  margin-bottom: 5px;
  margin-left: 10px;
  height: 48px;
  padding-left: 5px;
  line-height: 48px;
  /* width: 15%; */
  border-radius: 30px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
}
.number {
  display: block;
  height: 36px;
  margin-right: 20px;
  width: 400px;
  color: #303133;
  line-height: 36px;
  text-align: center;
  border: 1px solid #67c23a;
}
.container {
  display: flex;
  margin-left: 100px;
  margin-bottom: 10px;
  margin-top: 10px;
}
</style>


